package cn.sfrog.project.biz.admin.service.impl;

import cn.sfrog.common.constant.ConfigConstants;
import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.project.biz.admin.domain.BizUserAccount;
import cn.sfrog.project.biz.admin.domain.BizUserCommission;
import cn.sfrog.project.biz.admin.domain.BizUserRecharge;
import cn.sfrog.project.biz.admin.domain.vo.BizUserCommissionFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserCommissionQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizUserCommissionVO;
import cn.sfrog.project.biz.admin.enums.BizUserTradeTypeEnum;
import cn.sfrog.project.biz.admin.mapper.BizUserAccountMapper;
import cn.sfrog.project.biz.admin.mapper.BizUserCommissionMapper;
import cn.sfrog.project.biz.admin.service.IBizUserCommissionService;
import cn.sfrog.project.biz.admin.service.IBizUserTradeRecordService;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import cn.sfrog.system.mapper.SysUserMapper;
import cn.sfrog.system.service.ISysConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
 * 用户分佣记录Service业务层处理
 */
@Service
public class BizUserCommissionServiceImpl extends ServiceImpl<BizUserCommissionMapper, BizUserCommission> implements IBizUserCommissionService {
    @Resource
    private BizUserCommissionMapper bizUserCommissionMapper;
    @Resource
    private ISysConfigService sysConfigService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private BizUserAccountMapper bizUserAccountMapper;
    @Resource
    private IBizUserTradeRecordService bizUserTradeRecordService;



    /**
     * 查询用户分佣记录
     *
     * @param id 用户分佣记录主键
     * @return 用户分佣记录
     */
    @Override
    public BizUserCommissionVO selectBizUserCommissionById(Long id) {
        return bizUserCommissionMapper.selectBizUserCommissionById(id);
    }

    /**
     * 查询用户分佣记录列表
     *
     * @param query 用户分佣记录
     * @return 用户分佣记录
     */
    @Override
    public List<BizUserCommissionVO> selectBizUserCommissionList(BizUserCommissionQueryVO query) {
        if(query.getDateValue() != null){
            query.setStartTime(query.getDateValue()[0] + " 00:00:00");
            query.setEndTime(query.getDateValue()[1] + " 23:59:59");
        }
        return bizUserCommissionMapper.selectBizUserCommissionList(query);
    }

    /**
     * 新增用户分佣记录
     *
     * @param form 用户分佣记录
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizUserCommission(BizUserCommissionFormVO form) {
        BizUserCommission bizUserCommission = new BizUserCommission();
        BeanUtils.copyProperties(form, bizUserCommission);
        bizUserCommission.setCreateTime(new Date());
        bizUserCommission.setCreateBy(SecurityUtils.getUsername());
        bizUserCommission.setUpdateTime(new Date());
        bizUserCommission.setUpdateBy(SecurityUtils.getUsername());
        return bizUserCommission.insert();
    }

    /**
     * 修改用户分佣记录
     *
     * @param form 用户分佣记录
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizUserCommission(BizUserCommissionFormVO form) {
        BizUserCommission bizUserCommission = new BizUserCommission();
        BeanUtils.copyProperties(form, bizUserCommission);
        bizUserCommission.setUpdateTime(new Date());
        bizUserCommission.setUpdateBy(SecurityUtils.getUsername());
        return bizUserCommission.updateById();
    }

    /**
     * 批量删除用户分佣记录
     *
     * @param ids 需要删除的用户分佣记录主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizUserCommissionByIds(Long[] ids) {
            return BizUserCommission.DAO.delete(Wrappers.lambdaQuery(BizUserCommission.class).in(BizUserCommission::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
      //  return BizUserCommission.DAO.update(Wrappers.lambdaUpdate(BizUserCommission.class).in(BizUserCommission::getId, (Object[]) vo.getIds()).set(BizUserCommission::getStatus, vo.getStatus()));
        return true;
    }

    @Override
    public Boolean saveUserCommission(BizUserRecharge recharge, SysUser user) {
        if(StringUtils.isNotNull(user.getParentUserId())){
            //分佣给上级 1.获取分佣比例
            String firstDistribution = sysConfigService.selectConfigByKey(ConfigConstants.FIRST_DISTRIBUTION_SCALE);
            BigDecimal firstDistributionScale = new BigDecimal(firstDistribution).divide(new BigDecimal("100"));
            BizUserCommission bizUserCommission = buildEntity(user.getParentUserId(), recharge, 1, firstDistributionScale);
            bizUserCommissionMapper.insert(bizUserCommission);
            //修改上级的账户余额
            updateUserAccount(user.getParentUserId(),bizUserCommission.getCommissionAmount());
            //记录用户交易记录
            bizUserTradeRecordService.saveUserTradeRecord(user.getParentUserId(),bizUserCommission.getCommissionAmount(), BizUserTradeTypeEnum.DISTRIBUTION.getCode(),recharge.getSerialNumber(),"分销");
        }
        if(StringUtils.isNotNull(user.getTopUserId())){
            //分佣给上上级 1.获取分佣比例
            String secondDistribution = sysConfigService.selectConfigByKey(ConfigConstants.SECOND_DISTRIBUTION_SCALE);
            BigDecimal secondDistributionScale = new BigDecimal(secondDistribution).divide(new BigDecimal("100"));
            BizUserCommission bizUserCommission = buildEntity(user.getTopUserId(), recharge, 2, secondDistributionScale);
            bizUserCommissionMapper.insert(bizUserCommission);
            //修改上上级的账户余额
            updateUserAccount(user.getTopUserId(),bizUserCommission.getCommissionAmount());
            //记录用户交易记录
            bizUserTradeRecordService.saveUserTradeRecord(user.getTopUserId(),bizUserCommission.getCommissionAmount(), BizUserTradeTypeEnum.DISTRIBUTION.getCode(),recharge.getSerialNumber(),"分销");
        }
        return true;
    }
    public BizUserCommission buildEntity(Long userId,BizUserRecharge recharge,Integer level,BigDecimal firstDistributionScale){
        BizUserCommission bizUserCommission = new BizUserCommission();
        bizUserCommission.setUserId(userId);
        bizUserCommission.setSource(BizUserCommission.TYPE_RECHARGE);
        bizUserCommission.setRechargeId(recharge.getId());
        bizUserCommission.setRechargeUserId(recharge.getUserId());
        bizUserCommission.setRechargeAmount(recharge.getRechargeAmount());
        bizUserCommission.setCommissionLevel(level);
        bizUserCommission.setCommissionAmount(recharge.getRechargeAmount().multiply(firstDistributionScale));
        bizUserCommission.setCreateBy("admin");
        bizUserCommission.setCreateTime(DateUtils.getNowDate());
        bizUserCommission.setUpdateBy("admin");
        bizUserCommission.setUpdateTime(DateUtils.getNowDate());
        return bizUserCommission;
    }

    public void updateUserAccount(Long userId,BigDecimal commissionAmount){
        LambdaQueryWrapper<BizUserAccount> queryWrapper1 = new LambdaQueryWrapper<BizUserAccount>()
                .eq(BizUserAccount::getUserId, userId);
        BizUserAccount bizUserAccount = BizUserAccount.DAO.selectOne(queryWrapper1);
        if(StringUtils.isNotNull(bizUserAccount)){
            bizUserAccount.setCommissionAmount(bizUserAccount.getCommissionAmount().add(commissionAmount));
            bizUserAccount.setUpdateTime(DateUtils.getNowDate());
            bizUserAccount.setUpdateBy(bizUserAccount.getCreateBy());
            bizUserAccountMapper.updateById(bizUserAccount);
        }
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        SysUser userEntity = new SysUser();
        userEntity.setUserId(sysUser.getUserId());
        userEntity.setEscortBeanCount(bizUserAccount.getAccountBalance().add(bizUserAccount.getGiveAwayAmount()).add(bizUserAccount.getCommissionAmount()));
        sysUserMapper.updateUser(userEntity);
    }
}
